<!-- ChangeSalesmanDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="640px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    @closed="onClosed"
  >
    <div class="change-salesman-container">
      <!-- 客户信息 -->
      <div class="section customer">
        <h4 class="section-title">
          <el-icon><UserFilled /></el-icon>
          客户信息
        </h4>
        <div class="info-grid">
          <div class="info-item">
            <label>客户姓名</label>
            <span>{{ customDetails.customerName || '--' }}</span>
          </div>
          <div class="info-item">
            <label>联系电话</label>
            <span>{{ customDetails.customerPhone || '--' }}</span>
          </div>
          <div class="info-item full">
            <label>联系地址</label>
            <span>{{ customDetails.contactAddress || '--' }}</span>
          </div>
          <div class="info-item">
            <label>历史订单数</label>
            <el-tag size="small" type="success" effect="light">
              平台 {{ customDetails.sysCount || 0 }}
            </el-tag>
            <span class="ml-10"></span>
            <el-tag size="small" type="success" effect="light">
              复购 {{ customDetails.reCount || 0 }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 旧业务员信息（支持无绑定） -->
      <div class="section old-salesman">
        <h4 class="section-title" :class="{ warning: hasOldSalesman }">
          <template v-if="hasOldSalesman">
            <el-icon><Collection /></el-icon>
            当前绑定业务员
          </template>
          <template v-else>
            <el-icon><WarningFilled /></el-icon>
            当前状态
          </template>
        </h4>

        <template v-if="hasOldSalesman">
          <div class="salesman-card">
            <el-avatar :size="48" :src="customDetails.avatar" @error="true">
              {{ customDetails.salesmanName?.charAt(0) }}
            </el-avatar>
            <div class="details">
              <div class="name">{{ customDetails.salesmanName }}</div>
              <div class="meta">
                <span>电话：{{ customDetails.salesman.salesmanPhone || '未填写' }}</span>
                <span>部门：{{ customDetails.salesman.dept.deptName || '未分配' }}</span>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="empty-state">
            <el-icon><Promotion /></el-icon>
            <span>该客户尚未绑定任何业务员</span>
          </div>
        </template>
      </div>
      <!-- 新业务员选择 -->
      <div class="section new-salesman">
        <h4 class="section-title">
          <el-icon><Position /></el-icon>
          选择新业务员
        </h4>
        <el-select
          v-model="selectedSalesmanId"
          filterable
          remote
          reserve-keyword
          placeholder="输入姓名或账号搜索业务员"
          :remote-method="handleSearchSalesman"
          :loading="loading"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="item in salesmanList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          >
            <div class="select-option">
              <el-avatar :size="32" :src="item.avatar" @error="true">
                {{ item.nickName?.charAt(0) }}
              </el-avatar>
              <span class="name">{{ item.nickName }}</span>
              <span class="phone">{{ item.userName }}</span>
            </div>
          </el-option>
        </el-select>
      </div>

      <!-- 更换提示 -->
      <div v-if="showChangeTip" class="tip">
        <el-alert :title="changeTipText" type="info" show-icon :closable="false" center />
      </div>
    </div>

    <!-- 操作按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel" :disabled="loading">取 消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitting"
          :disabled="!selectedSalesmanId"
        >
          确认更换
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import {
  UserFilled,
  Collection,
  WarningFilled,
  Position,
  Promotion
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { updateCustomerSalesman } from '../../api/customers';

const props = defineProps<{
  salesmanList: any[];
}>();

const emit = defineEmits(['ok', 'search']);

// ================== 响应式数据 ==================
const visible = ref(false);
const customDetails = ref<any>({});
const loading = ref(false);
const submitting = ref(false);
const selectedSalesmanId = ref<string | null>(null);

// ================== 计算属性 ==================
const hasOldSalesman = computed(() => !!customDetails.value.salesmanId);

const dialogTitle = computed(() => {
  return `分配客户「${customDetails.value.customerName || '未知客户'}」的业务员`;
});

const selectedSalesman = computed(() =>
  props.salesmanList.find((item) => item.userId === selectedSalesmanId.value)
);

const showChangeTip = computed(() => {
  return (
    selectedSalesmanId.value &&
    (!customDetails.value.salesmanId || // 原本无绑定
      selectedSalesmanId.value !== customDetails.value.salesmanId) // 原有但更换
  );
});

const changeTipText = computed(() => {
  const oldName = customDetails.value.salesmanName || '无';
  const newName = selectedSalesman.value?.nickName || '未知';
  return `即将把客户「${customDetails.value.customerName}」的业务员从「${oldName}」更换为「${newName}」`;
});
// ================== 方法 ==================
const handleSearchSalesman = (keyword: string) => {
  if (!keyword.trim()) return;
  loading.value = true;
  setTimeout(() => {
    emit('search', keyword.trim());
    loading.value = false;
  }, 300);
};

const handleCancel = () => {
  visible.value = false;
};

const handleSubmit = async () => {
  if (!selectedSalesmanId.value || submitting.value) return;

  const oldName = customDetails.value.salesmanName || '无';
  const newName = selectedSalesman.value!.nickName;

  // 封装一个执行更新的方法
  const doUpdate = async () => {
    try {
      submitting.value = true;
      const res: any = await updateCustomerSalesman({
        customerId: customDetails.value.customerId,
        salesmanId: selectedSalesmanId.value
      });

      submitting.value = false;
      visible.value = false;

      if (res.code === 200) {
        emit('ok', selectedSalesmanId.value!);
        ElMessage.success('业务员更换成功');
      }
    } catch (err) {
      submitting.value = false;
      visible.value = false;
    }
  };

  // 如果之前没有业务员，直接更新
  if (oldName === '无') {
    return doUpdate();
  }

  // 二次确认
  try {
    await ElMessageBox.confirm(
      `确定将客户「${customDetails.value.customerName}」的业务员从「${oldName}」更换为「${newName}」吗？`,
      '更换确认',
      {
        type: 'warning',
        confirmButtonText: '确定更换',
        cancelButtonText: '再想想'
      }
    );

    await doUpdate();
  } catch {
    ElMessage.info('已取消操作');
  }
};

const onClosed = () => {
  selectedSalesmanId.value = null;
  loading.value = false;
};

const show = (row: any) => {
  customDetails.value = { ...row };
  visible.value = true;
};

const close = () => {
  visible.value = false;
};

defineExpose({ show, close });
</script>

<style scoped lang="scss">
$border-color: #e1e4e8;
$warning-color: #e6a23c;
$primary-color: #409eff;
$radius: 12px;

.change-salesman-container {
  padding: 16px 24px;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  color: #2c3e50;
  line-height: 1.5;
}

.section {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f1f3;

  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2328;
  margin: 0 0 14px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  letter-spacing: 0.2px;

  &.warning {
    color: $warning-color;
  }
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 14px;
}

.info-item {
  label {
    display: block;
    font-size: 13px;
    color: #555;
    margin-bottom: 4px;
    font-weight: 500;
  }

  span {
    font-size: 14px;
    color: #1f2328;
    word-break: break-word;
  }

  &.full {
    grid-column: span 2;
  }
}

// 旧业务员卡片
.salesman-card {
  display: flex;
  align-items: center;
  background: linear-gradient(to right, #f9fafb, #f8f9fa);
  border: 1px solid #eaecef;
  border-radius: $radius;
  padding: 14px;
  gap: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);

  .details {
    flex: 1;
    .name {
      font-weight: 600;
      color: #1f2328;
      font-size: 15px;
      margin-bottom: 4px;
    }
    .meta {
      font-size: 13px;
      color: #6c757d;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
}

// 空状态
.empty-state {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 16px;
  background: #fdf6ec;
  border: 1px dashed $warning-color;
  border-radius: $radius;
  color: $warning-color;
  font-size: 14px;
  font-weight: 500;
}

// 下拉选项
.select-option {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;

  .name {
    flex: 1;
    font-weight: 500;
    color: #1f2328;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .phone {
    font-size: 12px;
    color: #888;
    white-space: nowrap;
  }
}

// 提示
.tip {
  margin-top: 8px;
  :deep(.el-alert) {
    border-radius: 8px;
    font-size: 13.5px;
  }
}

// 按钮
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 10px;

  .el-button {
    min-width: 90px;
    font-weight: 500;
    border-radius: 8px;
    padding: 10px 20px;
  }
}

// 弹窗内边距优化
:deep(.el-dialog__body) {
  padding: 24px 20px 16px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-tag) {
  border-radius: 6px;
}
</style>
